package com.gyh.redisdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Locale;
import java.util.Map;

@Controller
public class NewsController {
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/detail/{id}")
public String detail(@PathVariable Integer id, Model model){

        //阅读数+1
       redisTemplate.opsForHash().increment("new_" + id, "read", 1);
        //查一下点赞数
        Map map = redisTemplate.opsForHash().entries("new_" + id);//new_id这个对象里的所有属性一次性查出
        model.addAllAttributes(map);
        return "new"+id;
    }

    //点赞 取消点赞
    @GetMapping("/addZan/{id}/{opType}")
    @ResponseBody
    public Long addZan(@PathVariable Integer id,@PathVariable Integer opType){
        Long countZan;
        if (opType==1){
            countZan=redisTemplate.opsForHash().increment("new_" + id, "countZan", 1);
        }else {
            countZan=redisTemplate.opsForHash().increment("new_" + id, "countZan", -1);
        }
        return countZan;
    }

}
